<script setup lang="ts">
import {CascaderProps, Modal} from 'ant-design-vue'
import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import type { CustomerModel } from '@/api/customer/customer-list.ts'
import { getCustomerList, delCustomerInfo } from '@/api/customer/customer-list.ts'
import dayjs from 'dayjs'
import CustomerAdd from './components/customer-add.vue'
import { getProvincesCities } from '@/api/common/common.ts'

const genderMap = {
  O: '未设定',
  1: '男',
  2: '女',
}

const customerMap = {
  1: '采购类客户',
  2: '销售类客户',
}

const message = useMessage()
const columns = shallowRef([
  {
    title: '客户编号',
    dataIndex: 'customerId',
  },
  {
    title: '客户名称',
    dataIndex: 'name',
  },
  {
    title: '客户类型',
    dataIndex: 'customerType',
  },
  {
    title: '客户性别',
    dataIndex: 'gender',
  },
  {
    title: '类型描述',
    dataIndex: 'description',
  },
  {
    title: '所属省份',
    dataIndex: 'provinceId',
  },
  {
    title: '所属城市',
    dataIndex: 'cityId',
  },
  {
    title: '具体地址',
    dataIndex: 'address',
  },
  {
    title: '建档时间',
    dataIndex: 'number',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 200,
  },
])
const loading = shallowRef(false)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: 10,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总数据位：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
// 客户列表数据
const dataSource = shallowRef<CustomerModel>([])
const dataCount = ref<number>(0)

const formModel = reactive<CustomerModel>({
  name: undefined,
})


const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})


async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const res = await getCustomerList({
      ...formModel,
      pageNumber: pagination.current,
      pageSize: pagination.pageSize,
    })
    console.log(res)
    if (res.code==200){
      console.log("成功获取到客户信息")
      console.log(res.data.list)
      dataSource.value =  res.data?.list?? []
      pagination.total = res.data?.count
    }else {
      message.error("获取客户信息失败")
    }

    const { data } = await getProvincesCities()
    allAreasList.value = data?? []
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
const customerAdd = ref<InstanceType<typeof CustomerAdd>>()

async function handleAdd(){
  customerAdd.value?.open()
}

async function handleEdit(record){
  //TODO 待补充仓库类型编号
  customerAdd.value?.open(record)
}

async function onSearch() {
  pagination.current = 1
  await init()
}

async function onReset() {
  // 清空所有参数重新请求
  formModel.name = ""
  formModel.provinceId = 0
  formModel.cityId = 0
  formModel.customerType = undefined
  await init()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: CustomerModel) {
  const close = message.loading('删除中......')
  try {
    const res = await delCustomerInfo(record)
    if (res.code === 200)
      await init()
    message.success('删除成功')
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

/**
 * 全选/反选事件
 *
 */

function handleCheckAllChange(e: any) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}

watch(
    () => state.checkList,
    (val) => {
      state.indeterminate = !!val.length && val.length < getCheckList.value.length
      state.checkAll = val.length === getCheckList.value.length
    },
)

/**
 * 重置事件
 *
 */
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}

/**
 * checkbox点击事件
 *
 */
function handleCheckChange(value: any) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}

function formattedDate(timestamp: string) {
  return dayjs(Number(timestamp) * 1000).format('YYYY-MM-DD HH:mm:ss')
}
/*
function getProvinceName(provinceId: number){
    return allAreasList.value.find(item => item.value === provinceId)[0].label
}*/

// 省市区所有数据
const allAreasList = shallowRef<CascaderProps>([])


const changeArea = (vl: any) => {
  formModel.provinceId = vl[0]?? 0;
  formModel.cityId = vl[1]?? 0;
}

onMounted(() => {
  init()
})
</script>

<template>
  <page-container>
    <a-card mb-4>
      <a-form :label-col="{ span: 7 }" :model="formModel">
        <a-row :gutter="[15, 0]">
          <a-col :span="4">
            <a-form-item name="name" label="客户名称">
              <a-input v-model:value="formModel.name" />
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="name" label="省份/城市">
              <a-cascader :options="allAreasList" placeholder="请选择省份/城市" @change="changeArea"/>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-form-item name="customerType" label="客户类型">
              <a-select v-model:value="formModel.customerType" placeholder="请选择客户类型" allowClear="true">
                <a-select-option value="1">
                  采购类客户
                </a-select-option>
                <a-select-option value="2">
                  销售类客户
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-space flex justify-end w-full>
              <a-button :loading="loading" type="primary" @click="onSearch">
                查询
              </a-button>
              <a-button :loading="loading" @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card title="客户列表">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            添加新客户
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
          <a-tooltip title="列设置">
            <a-dropdown v-model:open="dropdownVisible" trigger="click">
              <SettingOutlined />
              <template #overlay>
                <a-card>
                  <template #title>
                    <a-checkbox v-model:checked="state.checkAll" :indeterminate="state.indeterminate" @change="handleCheckAllChange">
                      列选择
                    </a-checkbox>
                  </template>
                  <template #extra>
                    <a-button type="link" @click="handleResetChange">
                      重置
                    </a-button>
                  </template>
                  <a-checkbox-group v-model:value="state.checkList" :options="options" style="display: flex; flex-direction: column;" @change="handleCheckChange" />
                </a-card>
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-error @click="handleDelete(scope?.record as CustomerModel)">
                删除
              </a>
              <a @click="handleEdit(scope?.record as CustomerModel)">
                编辑
              </a>
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'customerType'">
            <div gap-2>
              {{ customerMap[scope?.record?.customerType as keyof typeof customerMap] as string }}
            </div>
          </template>
          <!--          <template v-if="scope?.column?.dataIndex === 'parentTypeId'">
                      <div gap-2>
                        {{ dataSource[scope?.record?.parentTypeId as keyof typeof dataSource] as string }}
                      </div>
                    </template>-->
          <template v-if="scope?.column?.dataIndex === 'gender'">
            <div gap-2>
              {{ genderMap[scope?.record?.gender as keyof typeof genderMap] as string }}
            </div>
          </template>
          <template v-if="scope?.column?.dataIndex === 'recordTime'">
            <div gap-2>
              {{ formattedDate(scope?.record?.recordTime) }}
            </div>
          </template>
<!--          <template v-if="scope?.column?.dataIndex === 'provinceId'">
            <div gap-2>
              {{ getProvinceName(scope?.record?.provinceId) }}
            </div>
          </template>-->
        </template>
      </a-table>
    </a-card>
    <CustomerAdd ref="customerAdd" />
  </page-container>
</template>
